<template>
  <view class="my-order" ref="container">
    <!--    <view class="header bg-color-red">
      <view class="picTxt acea-row row-between-wrapper">
        <view class="text">
          <view class="name">订单信息</view>
          <view
            >累计订单：{{ orderData.orderCount || 0 }} 总消费：￥{{
              orderData.sumPrice || 0
            }}</view
          >
        </view>
      </view>
    </view> -->

    <u-sticky bgColor="#fff">
      <u-tabs
        :list="tabList"
        :current="current"
        @click="tabClick"
        lineWidth="15"
        lineColor="#FF5900"
        :itemStyle="{ height: '80rpx' }"
        :inactiveStyle="{ fontSize: '28rpx' }"
        :activeStyle="{
          fontSize: '30rpx',
          color: '#1A1A1A',
          fontWeight: '500',
        }"
      ></u-tabs>
    </u-sticky>
    <swiper
      class="scroll-view-height"
      @change="swipeIndex"
      :current="current"
      :duration="300"
    >
      <swiper-item v-for="swiper in tabList" :key="swiper.id">
        <scroll-view
          scroll-y="true"
          class="scroll-view-height list-content"
          :refresher-enabled="pullSwitch"
          :refresher-triggered="pullLoading"
          :lower-threshold="100"
          :refresher-threshold="100"
          @scrolltolower="scrolltolower"
          @refresherrefresh="e => refresherrefresh(e)"
        >
          <!-- 退款售后列表 -->
          <view class="list" v-if="type == 4">
            <ListItem
              v-for="(item, index) in orderList"
              :key="index"
              :item="item"
            />
          </view>
          <!-- 其他 -->
          <view class="list" v-else-if="type != 5">
            <view
              class="item"
              v-for="(order, orderListIndex) in orderList"
              :key="orderListIndex"
            >
              <view class="" v-if="order.orderId">
                <view class="title acea-row row-between-wrapper">
                  <view class="acea-row row-middle">
                    <span
                      class="sign cart-color acea-row row-center-wrapper"
                      v-if="order.combinationId > 0"
                      >拼团</span
                    >
                    <span
                      class="sign cart-color acea-row row-center-wrapper"
                      v-if="order.seckillId > 0"
                      >秒杀</span
                    >
                    <span
                      class="sign cart-color acea-row row-center-wrapper"
                      v-if="order.bargainId > 0"
                      >砍价</span
                    >
                    <span
                      class="sign cart-color acea-row row-center-wrapper"
                      v-if="order.storeId > 0"
                      >门店</span
                    >
                    <text>单号 {{ order.orderId }}</text>
                  </view>
                  <view class="font-color-green">{{ getStatus(order) }}</view>
                </view>
                <view @click="goOrderDetails(order)">
                  <view
                    class="item-info acea-row row-between row-top"
                    v-for="(cart, cartInfoIndex) in order.cartInfo"
                    :key="cartInfoIndex"
                  >
                    <view
                      class="pictrue"
                      style="width: 160rpx; height: 160rpx; margin-right: 24rpx"
                    >
                      <image
                        :src="cart.productInfo.image"
                        @click.stop="
                          $yrouter.push({
                            path: '/packageShop/pages/shop/GoodsCon/index',
                            query: { id: cart.productInfo.id },
                          })
                        "
                        v-if="
                          cart.combinationId === 0 &&
                          cart.bargainId === 0 &&
                          cart.seckillId === 0
                        "
                      />
                      <image
                        :src="cart.productInfo.image"
                        @click.stop="
                          $yrouter.push({
                            path: '/packageShop/pages/activity/GroupDetails/index',
                            query: { id: cart.combinationId },
                          })
                        "
                        v-else-if="cart.combinationId > 0"
                      />
                      <image
                        :src="cart.productInfo.image"
                        @click.stop="
                          $yrouter.push({
                            path: '/packageShop/pages/activity/DargainDetails/index',
                            query: { id: cart.bargainId },
                          })
                        "
                        v-else-if="cart.bargainId > 0"
                      />
                      <image
                        :src="cart.productInfo.image"
                        @click.stop="
                          $yrouter.push({
                            path: '/packageShop/pages/activity/SeckillDetails/index',
                            query: { id: cart.seckillId },
                          })
                        "
                        v-else-if="cart.seckillId > 0"
                      />
                    </view>
                    <view class="text">
                      <view class="shopRight">
                        <view class="name line1">{{
                          cart.productInfo.storeName
                        }}</view>
                        <view class="money">
                          <view
                            v-if="order.payType != 'integral'"
                            class="priceUnitBox"
                          >
                            <text class="priceUnit">￥</text>
                            {{ cart.truePrice }}
                          </view>
                          <view v-if="order.payType == 'integral'"
                            >{{ order.payIntegral }}积分</view
                          >
                        </view>
                      </view>

                      <view class="specification">
                        <view class="">{{
                          cart.productInfo.attrInfo.sku
                        }}</view>
                        <view>x{{ cart.cartNum }}</view>
                      </view>

                      <!-- <view class="time" v-if="!order.sameDayDeliveryPrice">
                      付款后，3天内发货
                    </view> -->
                    </view>
                  </view>
                </view>
                <!-- 		<view class="totalPrice">
                  共{{ order.cartInfo.length || 0 }}件商品，总金额
                  <text class="money font-color-red" v-if="order.payType != 'integral'">￥{{ order.payPrice }}</text>
                  <text class="money font-color-red" v-if="order.payType == 'integral'">{{ order.payIntegral }}积分</text>
                </view> -->
                <view class="priceBox">
                  <view class="priceBox-right">
                    <view class="vv1">
                      <text>总价</text>
                      <text class="price">{{ order.totalPrice || 0 }}</text>
                    </view>
                    <view class="vv3">
                      <text class="t1">实付款</text>
                      <text class="t2" v-if="order.payType != 'integral'">
                        <text class="t3">¥</text>
                        <text class="t4" v-if="order.payPrice">{{
                          String(order.payPrice.toFixed(2)).split('.')[0]
                        }}</text>
                        <text class="t5" v-else>0</text>
                        <text class="t5" v-if="order.payPrice"
                          >.{{
                            String(order.payPrice.toFixed(2)).split('.')[1]
                          }}</text
                        >
                      </text>
                      <text class="t2" v-if="order.payType == 'integral'">
                        <text class="t4" v-if="order.payPrice"
                          >{{ order.payIntegral }}积分</text
                        >
                      </text>
                    </view>
                  </view>
                </view>

                <view
                  class="bottom acea-row row-right row-middle"
                  v-if="order._status"
                >
                  <template v-if="order._status._type == 0">
                    <view
                      class="bnt cancelBnt btnStyle1"
                      @click="cancelOrder(order)"
                      >取消订单</view
                    >
                    <view
                      class="bnt bg-color-red btnStyle2"
                      @click="goOrderDetails(order)"
                      >立即付款</view
                    >
                  </template>
                  <template
                    v-else-if="
                      order._status._type === -1 ||
                      order._status._type == 1 ||
                      order._status._type === 4 ||
                      order._status._type == 9
                    "
                  >
                    <view
                      class="bnt bg-color-red btnStyle1"
                      @click="goOrderDetails(order)"
                      >查看详情</view
                    >
                  </template>
                  <template v-else-if="order._status._type == 2">
                    <view
                      class="bnt default btnStyle1"
                      @click="goLogistics(order)"
                      >查看物流</view
                    >
                    <view
                      class="bnt bg-color-red btnStyle1"
                      @click="takeOrder(order)"
                      >确认收货</view
                    >
                  </template>
                  <template v-else-if="order._status._type == 3">
                    <!--<view-->
                    <!--class="bnt default"-->
                    <!--@click="-->
                    <!--$yrouter.push({ path: '/packageShop/pages/order/Logistics/index',query:{id:order.orderId}})-->
                    <!--"-->
                    <!--v-if="order.deliveryType == 'express'"-->
                    <!--&gt;-->
                    <!--查看物流-->
                    <!--</view>-->
                    <view
                      class="bnt bg-color-red btnStyle1"
                      @click="goOrderDetails(order)"
                      >去评价</view
                    >
                  </template>
                </view>
              </view>
            </view>
          </view>
          <empty
            bgColor="rgb(248 248 248)"
            v-if="orderList.length === 0 && page > 1"
            ><p slot="content">暂无订单</p></empty
          >
        </scroll-view>
      </swiper-item>
    </swiper>

    <Loading :loaded="loaded" :loading="loading"></Loading>
    <Payment
      v-model="pay"
      :types="payType"
      @checked="toPay"
      :balance="userInfo.nowMoney"
    ></Payment>
  </view>
</template>
<script>
import { getOrderData, getOrderList } from '@/api/order'
import {
  cancelOrderHandle,
  payOrderHandle,
  takeOrderHandle,
} from '@/libs/order'
import Loading from '@/components/Loading'
import Payment from '@/components/Payment'
import empty from '@/components/empty'
import { mapGetters } from 'vuex'
import { isWeixin, dataFormat } from '@/utils'
import { getAfterSealsList } from '@/api/aftersales.js'
import ListItem from './ListItem.vue'
const STATUS = [
  '待付款',
  '待发货',
  '待收货',
  // '待评价',
  '已完成',
  '',
  '',
  '',
  '',
  '待付款',
]

const NAME = 'MyOrder'

export default {
  name: NAME,
  data() {
    return {
      pullLoading: true, //下拉刷新标识
      pullSwitch: true, //开启自定义下拉刷新

      offlinePayStatus: 2,
      orderData: {},
      type: 0, //type 是接口参数的类型
      current: 1, // 当前滑块的位置
      page: 1,
      limit: 20,
      loaded: false,
      loading: false,
      orderList: [],
      pay: false,
      payType: ['yue', 'weixin'],
      from: this.$deviceType,
      tabList: [
        {
          type: -1,
          name: '全部',
          id: null,
          orderList: [],
          pageNum: 1,
          total: 0,
          loadingType: 'more',
        },
        {
          type: 0,
          name: '待付款',
          id: null,
          orderList: [],
          pageNum: 1,
          total: 0,
          loadingType: 'more',
        },
        {
          type: 1,
          name: '待发货',
          id: null,
          orderList: [],
          pageNum: 1,
          total: 0,
          loadingType: 'more',
        },
        {
          type: 2,
          name: '待收货',
          id: null,
          orderList: [],
          pageNum: 1,
          total: 0,
          loadingType: 'more',
        },
        {
          type: 3,
          name: '待评价',
          id: null,
          orderList: [],
          pageNum: 1,
          total: 0,
          loadingType: 'more',
        },
        {
          type: 4,
          name: '退款/售后',
          id: null,
          orderList: [],
          pageNum: 1,
          total: 0,
          loadingType: 'more',
        },
      ],
    }
  },
  components: {
    Loading,
    Payment,
    empty,
    ListItem,
  },
  computed: mapGetters(['userInfo']),
  onShow() {
    // 从全局变量或存储中恢复数据
    if (uni.getStorageSync('tempPageData')) {
      this.orderList = uni.getStorageSync('tempPageData')
      uni.removeStorageSync('tempPageData')
    }
    // this.type = parseInt(this.$yroute.query.type) || 0
    //this.changeType(this.type)
    // this.getOrderData()
    // this.getOrderList()
  },
  onLoad(options) {
    if (options.type) {
      if(this.type != options.type){
        this.type = options.type
      }
      this.changeType(this.type)

      //this.current = options.type*1 + 1
      //console.log(this.current)
      //console.log("options.type*1+1 ="+(options.type*1+1))
    }

  },
  onHide: function () {
    this.orderList = []
    this.page = 1
    this.limit = 20
    this.loaded = false
    this.loading = false
  },
  methods: {
    //顶部tab点击
    tabClick(e) {
      // this.current = e.index
      console.log("e.index=")
      console.log(e)
      this.changeType(e.type)
      // console.log("this.current="+this.current)
    },
    // 下拉刷新
    refresherrefresh(e) {
      console.log(e, '自定义下拉刷新被触发')
      this.orderList = []
      this.page = 1
      this.loaded = false
      this.loading = false
      this.pullLoading = true
      this.$nextTick(() => {
        this.scrolltolower()
      })
    },
    // 下拉滚动
    scrolltolower() {
      console.log('下拉滚动=============')
      if (this.type == 4) {
        //售后
        !this.loading && this.getAfterSealsList()
      } else {
        !this.loading && this.getOrderListData()
      }
    },
    swipeIndex(e) {
      let _type = this.tabList[e.detail.current].type
      //this.type = this.tabList[e.detail.current].type
      _type!= this.type ? this.changeType(_type) : ''
      // if (this.loading || this.loaded) return
      //this.changeType(this.type)
    },

    goLogistics(order) {
      this.$yrouter.push({
        path: '/packageShop/pages/order/Logistics/index',
        query: { id: order.orderId },
      })
    },
    goOrderDetails(order) {
      // 跳转前保存数据
      uni.setStorageSync('tempPageData', this.orderList)
      this.$yrouter.push({
        path: '/packageShop/pages/order/OrderDetails/index',
        query: { id: order.orderId },
      })
    },
    dataFormat,
    setOfflinePayStatus: function (status) {
      var that = this
      that.offlinePayStatus = status
      if (status === 1) {
        if (that.payType.indexOf('offline') < 0) {
          that.payType.push('offline')
        }
      }
    },
    getOrderData() {
      getOrderData().then(res => {
        this.orderData = res.data
      })
    },
    takeOrder(order) {
      takeOrderHandle(order.orderId).finally(() => {
        this.reload()
        // this.getOrderData()
      })
    },
    reload() {
      this.changeType(this.type)
    },

    changeType(type) {
      console.log('changeType', type, this.type, '------------------------')
      // if (type == this.type) return
      this.type = type
      this.current = type*1 + 1
      console.log("最终current="+this.current)
      this.orderList = []
      this.page = 1
      this.loaded = false
      this.loading = false
      if (type == 4) {
        this.getAfterSealsList()
      } else {
        this.getOrderListData()
      }
    },
    getOrderListData() {
      if (this.loading || this.loaded) return
      this.loading = true
      const { page, limit, type } = this

      getOrderList({
        page,
        limit,
        type: this.type,
      }).then(res => {
        this.orderList = this.orderList.concat(res.data)
        // 看不懂为啥要调用这个  先注释  20250804
        // if (this.type == -1) {
        //   getAfterSealsList({
        //     page,
        //     limit,
        //     type: 0,
        //   }).then(resList => {
        //     this.orderList = this.orderList.concat(resList.data)
        //   })
        // }

        this.page++
        this.loaded = res.data.length < this.limit
        this.loading = false
        this.pullLoading = false
      })
    },
    // 售后列表
    getAfterSealsList() {
      if (this.loading || this.loaded) return
      this.loading = true
      const { page, limit } = this
      getAfterSealsList({
        page,
        limit,
        type: 0,
      }).then(res => {
        this.orderList = this.orderList.concat(res.data)
        this.page++
        this.loaded = res.data.length < this.limit
        this.loading = false
        this.pullLoading = false
      })
    },
    getStatus(order) {
      if (order._status) {
        //         if(order._status._type == -1) {
        // return
        //         } else  return STATUS[order._status._type]
        return order._status._title || ''
      } else {
        return ''
      }
    },
    cancelOrder(order) {
      cancelOrderHandle(order.orderId)
        .then(() => {
          // this.getOrderData()
          this.orderList.splice(this.orderList.indexOf(order), 1)
        })
        .catch(() => {
          this.reload()
        })
    },
    paymentTap: function (order) {
      var that = this
      if (
        !(order.combinationId > 0 || order.bargainId > 0 || order.seckillId > 0)
      ) {
        that.setOfflinePayStatus(order.offlinePayStatus)
      }
      this.pay = true
      this.toPay = type => {
        payOrderHandle(order.orderId, type, that.from)
          .then(() => {
            const type = parseInt(this.$yroute.query.type) || 0
            that.changeType(type)
            // that.getOrderData()
          })
          .catch(() => {
            const type = parseInt(that.$yroute.query.type) || 0
            that.changeType(type)
            // that.getOrderData()
          })
      }
    },
    toPay() {},
  },
}
</script>

<style scoped lang="less">
.noCart {
  // margin-top: 0.17 * 100rpx;
  // padding-top: 0.1 * 100rpx;
  overflow: hidden;
}

.noCart .pictrue {
  width: 4 * 100rpx;
  height: 3 * 100rpx;
  overflow: hidden;
  margin: 0.7 * 100rpx auto 0.5 * 100rpx auto;
}

.noCart .pictrue image {
  width: 4 * 100rpx;
  height: 3 * 100rpx;
}

.priceUnitBox {
  font-size: 28rpx;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #1a1a1a;
  line-height: 40rpx;
  .priceUnit {
    font-size: 18rpx;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #1a1a1a;
    line-height: 24rpx;
  }
}

.shopRight {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.specification {
  margin-top: 8rpx;

  font-size: 28rpx;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #999999;
  line-height: 40rpx;

  display: flex;
  justify-content: space-between;
  align-items: center;
}

.time {
  margin-top: 13rpx;
  display: inline-block !important;
  // width: 202px;
  height: 32rpx;
  border-radius: 8rpx;
  border: 1px solid #ff6010;
  padding: 0px 6rpx;

  font-size: 22rpx;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #ff6010;
  line-height: 30rpx;
}
.priceBox {
  padding-left: 24rpx;
  padding-right: 24rpx;
  padding-bottom: 7rpx;
  display: flex;
  justify-content: flex-end;

  .priceBox-right {
    display: flex;
    vertical-align: bottom;
    align-items: baseline;

    text {
      font-size: 24rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      line-height: 32rpx;
    }

    view {
      margin-left: 16rpx;
    }

    .vv1 {
      line-height: 50rpx;
    }

    .vv2 {
      line-height: 50rpx;
    }

    .price {
      margin-left: 8rpx;
    }

    .t1 {
      font-size: 24rpx;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #333333;
      line-height: 32rpx;
    }

    .t2 {
      margin-left: 8rpx;
    }

    .t3 {
      font-size: 24rpx;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #333333;
      line-height: 32rpx;
    }

    .t4 {
      font-size: 36rpx;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #333333;
      line-height: 50rpx;
    }

    .t5 {
      font-size: 24rpx;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #333333;
      line-height: 32rpx;
    }
  }
}

.btnStyle1 {
  font-weight: 400 !important;
  background-color: #fff !important;
  border: 2rpx solid #e6e6e6 !important;
  line-height: 54rpx !important;
  color: #666666 !important;
}

.btnStyle2 {
  font-weight: 400 !important;
  background-color: #fff !important;
  color: #FF5900 !important;
  border: 2rpx solid #FF5900 !important;
  line-height: 54rpx !important;
}
.bg-color-orgin {
  background-color: #FF5900;
}

.nav {
  position: relative;
  z-index: 99;
  .itemT {
    font-size: 28rpx;
    color: #1a1a1a;
    font-weight: 500;
    transform: all 0.3s;
  }
}

.scroll-view-height {
  height: calc(100vh - 120rpx);
  // background-color: pink;
}
</style>
